﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class MD5加密与签名 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    #region  加密及验证签名

    /// <summary>
    /// 进行验证签名
    /// </summary>
    /// <param name="signValue">签名</param>
    /// <returns></returns>
    private bool VerificationSign(string signValue)
    {
        bool bl = false;
        var allKeys = Request.Form.AllKeys.Concat(Request.QueryString.AllKeys).OrderBy(p => p).ToList();
        allKeys.Remove("sign");
        var urlParameters = new List<string>();
        foreach (var item in allKeys)
        {
            urlParameters.Add(item + "=" + Request.Params[item]);
        }
        if (GetMD5Hash(Server.UrlEncode(string.Join("&", urlParameters) + "d2a0ea1620de244c3e4427982bf36a34").ToUpper()).Substring(0, 32).ToLower() == signValue)
        {
            bl = true;
        }
        return bl;
    }

    /// <summary>
    /// MD5加密
    /// </summary>
    /// <param name="value">加密参数</param>
    /// <returns></returns>
    public static String GetMD5Hash(String value)
    {
        try
        {
            byte[] res = System.Text.Encoding.Default.GetBytes(value);
            MD5CryptoServiceProvider md = new MD5CryptoServiceProvider();
            byte[] result = md.ComputeHash(res);
            byte[] hash = md.ComputeHash(result);
            StringBuilder sbuilder = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                int v = hash[i] & 0xFF;
                if (v < 16) sbuilder.Append("0");
                sbuilder.Append(Convert.ToString(v, 16).ToUpper());
            }
            return sbuilder.ToString();
        }
        catch
        {
            return null;
        }
    }
    #endregion
}